package com.shelpe.services.sinbad.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.shelpe.services.sinbad.entity.jpa.Message;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.model.Creative;
import com.shelpe.services.sinbad.model.Product;
import com.shelpe.services.sinbad.model.RptCustomer;
import com.shelpe.services.sinbad.model.RptCustomerParam;
import com.shelpe.services.sinbad.model.RptKeywordParam;
import com.shelpe.services.sinbad.repository.jpa.MessageRepository;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;
import com.shelpe.services.sinbad.service.CreativeService;
import com.shelpe.services.sinbad.service.ProductService;
import com.shelpe.services.sinbad.service.RptCustomerService;
import com.shelpe.services.sinbad.service.RptKeywordService;
import com.shelpe.services.sinbad.service.simbaproxy.CreativeClient;
import com.shelpe.services.sinbad.service.simbaproxy.CreativeClient.CreativeDto;
import com.shelpe.services.sinbad.service.simbaproxy.CreativeClient.CreativeRespDto;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/sinbadservice/users")
@Slf4j
public class UserController {

	@Autowired
	ProductService productService;

	@Autowired
	CreativeClient creativeClient;

	@Autowired
	CreativeService creativeService;

	@Autowired
	RptCustomerService rptCustomerService;

	@Autowired
	RptKeywordService rptKeywordService;

	@Autowired
	MessageRepository messageRepository;

	@Autowired
	UserRepository userRepository;

	/**
	 * 创建信息
	 * 
	 * @param userID
	 * @param dto
	 * @return
	 */
	@RequestMapping(path = "/{user_id}/messages", method = RequestMethod.POST)
	@ResponseBody
	public MessageDto createMessage(@PathVariable("user_id") long userID, @RequestBody MessageDto dto) {
		Assert.notNull(userID, "user_not_found");
		User user = this.userRepository.findOne(userID);
		Message mess = new Message();
		BeanUtils.copyProperties(dto, mess);
		mess.setUserID(userID);
		mess.setNick(user.getNick());
		mess.setCreateTime(new Date());
		mess.setLastModifeTime(new Date());
		mess.setUnread(0);
		this.messageRepository.save(mess);
		log.debug("finish create message:{}", mess);
		dto.setInformID(mess.getInformID());

		return dto;
	}

	/**
	 * 查看所有信息
	 * 
	 * @param userID
	 * @param containerID
	 * @param unread
	 * @return
	 */
	@RequestMapping(path = "/{user_id}/messages", method = RequestMethod.GET)
	@ResponseBody
	public List<MessageDto> findMessage(@PathVariable("user_id") long userID,
			@RequestParam("container_id") long containerID,
			@RequestParam(required = false, defaultValue = "0") int unread) {
		List<Message> messages = this.messageRepository.findByUserIDAndContainerIDAndUnread(userID, containerID, unread);
		log.info("findMessage", messages.size());
		List<MessageDto> dtos = new ArrayList<MessageDto>();

		for (Message mess : messages) {
			MessageDto dto = new MessageDto();
			BeanUtils.copyProperties(mess, dto);

			dtos.add(dto);
		}
		return dtos;
	}

	/**
	 * 修改信息
	 * 
	 * @param userID
	 * @param messageID
	 */
	@RequestMapping(path = "/{user_id}/messages/{message_id}/@read", method = RequestMethod.PUT)
	@ResponseBody
	public void updateMessage(@PathVariable("user_id") long userID, @PathVariable("message_id") long messageID) {
		Message mess = this.messageRepository.findOne(messageID);
		Assert.notNull(mess, "mess_not_foud");

		log.debug("updateMessage: {}, {}", messageID);
		mess.setUnread(1);
		mess.setLastModifeTime(new Date());
		this.messageRepository.save(mess);
	}

	@Data
	@JsonInclude(Include.NON_NULL)
	public static class MessageDto {
		@JsonProperty("inform_id")
		private long informID;
		@JsonProperty("user_id")
		private long userID;
		private String nick;
		@JsonProperty("container_id")
		private long containerID;
		@JsonProperty("content_type")
		private String type;
		@JsonProperty("content")
		private String content;
		@JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
		private Date createTime;
		@JsonProperty("last_modife_time")
		@JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
		private Date lastModifeTime;
		private int unread;
		@JsonProperty("container_url")
		private String containerUrl;
	}

	/**
	 * 所有宝贝
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping("/{userId}/products")
	public @ResponseBody Object products(@PathVariable("userId") Long userId) {
		log.info("查询所有宝贝, 用户ID：{}", userId);
		return productService.getProducts(userId);
	}

	/**
	 * 宝贝详情
	 * 
	 * @param userId
	 * @param productId
	 * @return
	 */
	@RequestMapping("/{userId}/products/{productId}")
	public @ResponseBody Object product(@PathVariable("userId") Long userId,
			@PathVariable("productId") Long productId) {
		log.info("查询所有宝贝, 用户ID：{}, 产品ID：{}", userId, productId);
		Product product = productService.getProduct(productId);
		log.info("product:{}", JSON.toJSON(product));
		return product;
	}

	/**
	 * 同步创意到淘宝 并保存数据库
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/{userId}/adgroups/{adgroupId}/creatives")
	public @ResponseBody Object postCreatives(@PathVariable("userId") Long userId,
			@PathVariable("adgroupId") Long adgroupId, @RequestBody String dto) {
		log.info("同步创意到淘宝 userId:{} adgroupId:{}, {}", userId, adgroupId, dto);
		CreativeDto dt = new CreativeDto();
		dt = JSON.parseObject(dto, CreativeDto.class);
		CreativeRespDto rsp = creativeClient.postCreative(dt.getAdgroupId(), dt.getCreativeId(), dt.getTitle(),
				dt.getUrl(), dt.getNick());
		log.info("rsp：{}", rsp);
		if (rsp.getCreativeId() != null) {
			Creative creative = new Creative();
			BeanUtils.copyProperties(rsp, creative);
			log.info("creative：{}", creative);
			return creativeService.updateCreative(creative);
		} else {
			return "error";
		}
	}

	/**
	 * 同步关键词到淘宝 并保存数据库
	 * 
	 * @return
	 */
	@RequestMapping("/{userId}/adgroups/{adgroupId}/keyword")
	public @ResponseBody String postKeywords(@PathVariable("userId") Long userId,
			@PathVariable("adgroupId") Long adgroupId) {
		log.info("同步关键词到淘宝 userId:{} adgroupId:{}", userId, adgroupId);
		return null;
	}

	/**
	 * 指标摘要
	 * 
	 * @return
	 */
	@RequestMapping("/{userId}/summaries/metric")
	public @ResponseBody Object summariesMetric(@PathVariable("userId") Long userId,
			@RequestParam(required = false, defaultValue = "0") int device, @RequestParam String startDate,
			@RequestParam String endDate) {
		log.info("summariesMetric RequestParam userId:{} device:{} startDate:{} endDate:{}", userId, device, startDate,
				endDate);
		RptCustomerParam param = new RptCustomerParam();
		param.setTaobaoUserId(userId);
		param.setDevice(device);
		param.setStartDate(DateUtils.parseDate(startDate, new String[] { "yyyy-MM-dd" }));
		param.setEndDate(DateUtils.parseDate(endDate, new String[] { "yyyy-MM-dd" }));
		Object obj = rptCustomerService.selectSums(param);
		if (obj == null) {
			obj = new RptCustomer();
		}
		return obj;
	}

	/**
	 * 趋势
	 * 
	 * @return
	 */
	@RequestMapping("/{userId}/reports/trend")
	public @ResponseBody Object postKeywords1(@PathVariable("userId") Long userId,
			@RequestParam(defaultValue = "0") int device, @RequestParam String startDate,
			@RequestParam String endDate) {
		log.info("reportsTrend RequestParam userId:{} device:{} startDate:{} endDate:{}", userId, device, startDate,
				endDate);
		RptCustomerParam param = new RptCustomerParam();
		param.setTaobaoUserId(userId);
		param.setDevice(device);
		param.setStartDate(DateUtils.parseDate(startDate, new String[] { "yyyy-MM-dd" }));
		param.setEndDate(DateUtils.parseDate(endDate, new String[] { "yyyy-MM-dd" }));
		Object obj = rptCustomerService.selectStat(param);
		if (obj == null) {
			obj = new ArrayList<RptCustomer>();
		}
		return obj;
	}

	@RequestMapping("/{user_id}/campaignStates")
	public @ResponseBody Object campaignStates(@PathVariable("user_id") Long userId,
			@RequestParam(defaultValue = "7") Integer days, @RequestParam(required = false) Integer device,
			@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
		log.info("campaignStates RequestParam userId:{} days:{} device:{} startDate:{} endDate:{}", userId, days,
				device, startDate, endDate);
		RptKeywordParam param = new RptKeywordParam();
		param.setUserId(userId);
		param.setDay(days);
		if (device != null) {
			param.setSource(device.byteValue());
		}
		param.setStartDate(startDate);
		param.setEndDate(endDate);
		return rptKeywordService.getReportsTrend(param);
	}
}
